package com.example.hosptial.newController;

import com.example.hosptial.model.view.DoctorView;
import com.example.hosptial.service.DoctorManagementService;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 医生信息更新Controller
 */
@Controller
@RequestMapping("/doctor")
public class DoctorProfileController {

    private static final Logger logger = LoggerFactory.getLogger(DoctorProfileController.class);

    @Autowired
    private DoctorManagementService doctorService;

    /**
     * 显示医生个人信息页面
     */
    @GetMapping("/profile")
    public String showProfilePage(HttpSession session, Model model) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return "redirect:/doctor/auth/login";
        }
        model.addAttribute("doctor", doctor);
        return "doctor/doctor-info";
    }

    /**
     * 更新医生信息
     */
    @PostMapping("/update")
    public String updateDoctorInfo(
            @RequestParam String doctorId,
            @RequestParam String currentPassword,
            @RequestParam(required = false) String newPhone,
            @RequestParam(required = false) String newPassword,
            HttpSession session,
            RedirectAttributes redirectAttributes) {

        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return "redirect:/doctor/auth/login";
        }

        try {
            DoctorView updatedDoctor = doctorService.updateDoctorInfo(
                doctorId, currentPassword, newPhone, newPassword);
            
            // 更新session中的医生信息
            session.setAttribute("doctor", updatedDoctor);
            redirectAttributes.addFlashAttribute("success", "个人信息更新成功");
            return "redirect:/doctor/dashboard";

        } catch (IllegalArgumentException e) {
            logger.warn("更新医生信息参数错误: {}", e.getMessage());
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/doctor/dashboard";

        } catch (Exception e) {
            logger.error("更新医生信息失败: {}", e.getMessage());
            redirectAttributes.addFlashAttribute("error", "系统错误，请稍后重试");
            return "redirect:/doctor/dashboard";
        }
    }

    @RequestMapping("/dashboard")
    public String showDashboard(HttpSession session, Model model) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return "redirect:/doctor/auth/login";
        }
        model.addAttribute("doctor", doctor);
        return "doctor/dashboard";
    }
}